package control.hall
{
	import control.panel.PanelControl;
	
	import events.HallEvent;
	import events.LoginEvent;
	
	import flash.utils.Dictionary;
	
	import view.components.UIComponents;
	import view.hall.RoomsList;
	import global.GameState;

	public class RoomListControl extends PanelControl
	{
		private var roomsList:RoomsList;
		private var currentIndex:int = 0;
		private var dataProvider:*;
		
		
		public function RoomListControl()
		{
			initRoomsList();
			initListener();
			initDataProvider();
		}
		
		private function initDataProvider():void
		{
			dataProvider = UIComponents.getDataProvider();
		}
		
		private function initListener():void
		{
			_model.hallModel.addEventListener(HallEvent.ROOM_XML_COMPLETE,onRoomXmlComplete);
			_model.hallModel.addEventListener(HallEvent.SEARCH_COMPLETE,onSearchCompelte);
			
			if (GameState.DEBUG_STATE == 1)
			{
				_model.loginModel.addEventListener(LoginEvent.ACCESSSERVER_LOGINING,onAccessLogining);
			}
			else
			{
				_model.loginModel.addEventListener(LoginEvent.SUCCESS,onAccessLogining);
			}
		}
		
		private function onAccessLogining(event:LoginEvent):void
		{
			refressList();
		}
		
		private function onRoomXmlComplete(event:HallEvent):void
		{
			if (event.xmlType == currentIndex)
			{
			
				dataProvider.removeAll();
				dataProvider.merge(event.xml);
				roomsList.updateList(dataProvider);
				roomsList.hideLoading();
				
			}
			
		}
		
		private function onSearchCompelte(event:HallEvent):void
		{
			showRoomList(event.xml);
			
		}
		
		private function showRoomList(data:XML):void
		{
			dataProvider.removeAll();
			dataProvider.merge(data);
			roomsList.updateList(dataProvider);
			roomsList.hideLoading();
		}
		
		private function initRoomsList():void
		{
			roomsList = new RoomsList(this);
			roomsList.x = 8;
			roomsList.y = 210;
			_view.hallLayer.addChild(roomsList);
		}
		
		
		
		public function onTabSwitch(index:int):void
		{
			currentIndex = index;
			
			
			
			roomsList.clearList();
			roomsList.showLoading();
			
			
			_model.hallModel.sendRoomListRequest(index);
			_control.hallControl.switchToFastEnterHint();
		}
		
		public function onItemDClick():void
		{			
			GameState.isQuickGame = 0;
			enterRoom();
		}
		
		public function onItemClick(item:Object):void
		{
			if (item)
			{
				var gameServerId:String = item.serverId;
				var roomId:String = item.id;
				_control.playerListControl.sendRoomPlayerRequest(gameServerId,roomId);
				_control.hallControl.switchToEnterHint();
			}
		}
		
		public function enterRoom():void
		{
			var item:Object = roomsList.selectedItem;
			if (item)
			{
				var gameServerIp:String = item.ip;
				var port:int = int(item.port);
				var roomId:String = item.id;
				_model.loginModel.loginGameServer(roomId,gameServerIp,port);
			}
		}
		
		public function refressList():void
		{
			_model.hallModel.clearRoomXML(currentIndex);
			onTabSwitch(currentIndex);
		}
	}
}